package network_programming.np1_socket_and_serversocket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
    private int port = 9099;        // 监听的端口号
    private ServerSocket serverSocket;
    public EchoServer() throws IOException {
        serverSocket = new ServerSocket(port);  // 监听port端口
        System.out.println("服务器启动成功");
    }
    public String echo(String msg) {
        return "echo: " + msg;
    }
    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOS = socket.getOutputStream();   // 获取socket对象的输出流对象
        return new PrintWriter(socketOS, true);
            // PrintWriter中第二个参数true表示：当每写一行，PrintWriter缓存自动溢出，把数据写到目的地
    }
    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketIS = socket.getInputStream();     // 获取socket对象的输入流对象
        return new BufferedReader(new InputStreamReader(socketIS));
    }
    public void service() {
        while(true) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();     // 等待客户的连接请求
                System.out.println("New connection accepted " + socket.getInetAddress() +
                        ":" + socket.getPort());
                /**
                 * socket.getInetAddress()  获取远程被连接进程的ip地址
                 * socket.getPort()         获取远程被连接进程的端口
                 * socket.getLocalAddress() 获取本地的ip地址
                 * socket.getLocalPort()    获取本地的端口
                 * */
                BufferedReader br = getReader(socket);
                PrintWriter pw = getWriter(socket);
                String msg = null;
                while((msg = br.readLine()) != null) {
                    System.out.println("接收到：" + msg);
                    pw.println(echo(msg));
                    if(msg.equals("bye"))
                        break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(socket != null) {
                    try {
                        socket.close();     // 断开连接
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new EchoServer().service();
    }
}
